<?php
namespace backend\controller;
use backend\controller\BackendBaseController;
use backend\model\admin_access;
use backend\model\role_auth;
use backend\model\admin_role;
use jimu\Request;

class AdminroleController extends BackendBaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function indexAction()
    {
        if($_SESSION['admin']['role_id'] != admin_role::ROLE_ID_SUPERADMIN){
            return '没有权限';
        }
        $model = new admin_role();
        $list = $model->select();
        foreach($list AS  &$value){
            $value['status_name'] = admin_role::getConstValue('status',$value['role_status']);
        }

        $this->assign('list',$list);
        $this->assign('page_title','角色列表');
        $this->display('index');

    }

    public function authAction()
    {
        $model_role_auth = new role_auth();

        if($_POST){
            $model_role_auth->begin();
            try{
                $params = Request::post();
                $model_role_auth->saveRoleAuthData($params['role_id'],$params['access_ids']);
                $model_role_auth->commit();
                ajaxReturn(['code'=>1,'msg'=>'success']);
            }catch(\Exception $e){
                $model_role_auth->rollback();
                ajaxReturn(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
            }
        }
        $role_id = Request::get('id');

        $model = new admin_role();
        $role = $model->findOne($role_id);
        if(!$role){
            throw new \Exception('角色不存在',-2000);
        }

        $auth_list = $model_role_auth -> getRoleAuthData($role_id);
        $auth_list = array_values($auth_list);


        $this->assign('role_id',$role_id);
        $this->assign('role_name',$role['role_name']);
        $this->assign('auth_list',json_encode($auth_list,true));
        $this->assign('page_title','授权操作');
        $this->display('auth');

    }

    public function delAction()
    {
        $role_model = new admin_role();
        if($_POST){
            try{
                $params = Request::post();
                $role_id = $params['role_id'];
                $role_model->deleteRole($role_id);
                ajaxReturn(['code'=>1,'msg'=>'success']);
            }catch(\Exception $e){
                ajaxReturn(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
            }
        }
    }
}